package com.zhonglz.util.md5;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.springframework.util.DigestUtils;

import com.zhonglz.util.Constans;
import com.zhonglz.util.base64.Base64Utils;
import com.zhonglz.util.hex.HexUtils;
import com.zhonglz.util.sm4.Sm4Utils;

/****
 * md5摘要
 * @author xiaozhong
 *
 */
public class Md5Utils {
	
	public static String generateMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest digest = MessageDigest.getInstance("MD5");
		byte[] bs = digest.digest(str.getBytes("UTF-8"));
		StringBuilder sb = new StringBuilder(40);
		for (byte x : bs) {
			if ((x & 0xff) >> 4 == 0) {
				sb.append("0").append(Integer.toHexString(x & 0xff));
			} else {
				sb.append(Integer.toHexString(x & 0xff));
			}
		}
		return sb.toString();
	}
	
	public static String generateMd5(byte[] bytes) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest digest = MessageDigest.getInstance("MD5");
		byte[] bs = digest.digest(bytes);
		StringBuilder sb = new StringBuilder(40);
		for (byte x : bs) {
			if ((x & 0xff) >> 4 == 0) {
				sb.append("0").append(Integer.toHexString(x & 0xff));
			} else {
				sb.append(Integer.toHexString(x & 0xff));
			}
		}
		return sb.toString();
	}
	
	/**
	* 将密码执行加密
	* @param password 原密码
	* @return 加密后的结果
	*/
	public static String getMd5Password(String password) {
		String salt=Constans.SM4_KEY;//使用sm4对称加密得key作为盐值给密码加密
		// 拼接原密码与盐值
		String str = salt + password + salt;
		// 循环加密5次
		for (int i = 0; i < 5; i++) {
			// DigestUtils：springboot提供的工具类
			str = DigestUtils.md5DigestAsHex(str.getBytes()).toUpperCase();
		}
		// 返回结果
		return str;
	}

	
	public static void main(String[] args) throws Exception {
		String str= "admin123456";
		System.out.println("加密前："+str);
		String md5Str=Md5Utils.getMd5Password(str);
		System.out.println("加密后："+ md5Str);
		
		String md5Str1=Md5Utils.getMd5Password(str);
		System.out.println("加密后："+ md5Str1);
		
	}
}
